import { defineStore } from 'pinia'
import { appVersion } from '@/config'
import appData from '@/components/edit/template-data/app-data'
import cataData from '@/components/edit/template-data/cata-data'
import customTopNavData from '@/components/edit/template-data/widget-data/custom-top-nav'
import getCataDataPageFlat from '@/libs/edit/getCataDataPageFlat'
import getWidgetListFlat from '@/libs/edit/getWidgetListFlat'
import getWidgetHierarchys from '@/libs/edit/getWidgetHierarchys'
import getWidgetParentBindForm from '@/libs/edit/getWidgetParentBindForm'
import { createComponentAttr } from '@/libs/edit'
import { deepClone } from '@/libs/tools'
import { ElMessage } from 'element-plus'
import {
    getApp, getAppAliyun, getModuleMethod,
    saveApp, saveAppAliyun
} from '@/api/app'

// 风格
const style = {
    "button": "#409EFF",                    // 按钮
    "title-ele": "#409EFF",                 // 标题
    "breakline": "#f3f3f3",                 // 分割线
    "backgroundTextStyle": "dark",          // 下拉加载样式
    "windowBackgroundColor": "#ffffff",     // 窗口背景颜色 (下拉刷新的背景颜色)
    "navigationBarBackgroundColor": "#fff", // 顶部导航颜色
    "navigationBarTextStyle": "#000"        // 顶部导航文字颜色
}

const useEditStore = defineStore('edit', {
    state: () => ({
        appId: '', // appID
        historyId: '', // 当前历史ID
        appData, // 页面数据
        cataData, // 页面管理数据
        modulePageConfigs: {}, // 模块页面配置(type=3)

        appName: '', // 应用名称
        appDescription: '', // 应用描述
        appAvaterUrl: '', // 应用封面图
        isDynamicData: false, // 数据动态化状态
        style, // 风格

        pageId: 'page10000', // 当前操作的appData页面key值

        selectWidgetIds: [], // 当前选中的控件ID
        draggableWidget: { // 拖动的控件
            from: '', // 起始位置(template从模板列表开始拖动、list从列表开始拖动)
            widgetType: '', // 控件类型
            widgetId: '' // 控件ID
        },

        phoneZoom: 1.15, // 控件容器缩放倍数
        rulerVisible: false, // 量尺显示状态
        templateDrawerVisible: false, // 模板抽屉显示状态

        fxMethods: {} // 模型变量方法集
    }),
    getters: {
        // 入口页面
        homePageRouter: state => state.appData?.data?.['homepage-router'] || '',
        // 页面管理数据(扁平化)
        cataDataPageFlat: state => getCataDataPageFlat(state.cataData),
        // 底部导航数据
        tabbarData: state => state.appData?.data?.['tab-bar'] || {},

        // 当前页面数据
        pageData: state => state.appData?.[state.pageId] || {},
        // 当前页面类型(1原生页面(不可编辑)，2瓦立页面(可编辑)，3个性化页面(仅可配置))
        pageType(state) {
            return this.cataDataPageFlat?.[state.pageId]?.data?.type || 2
        },

        // 模块页面配置
        modulePageConfig(state) {
            return this.pageType === 3 ? (state.modulePageConfigs?.[state.pageId] || {}) : {}
        },

        // 当前页面控件列表
        widgetList() {
            return this.pageData?.eles || []
        },
        /**
         * 当前页面控件列表(扁平化)
         * 控件ID: { 控件数据, 控件索引, 父级控件Id, 父级控件内容, 是否是自由子控件, 控件的层级链, 父级控件绑定的form  }
         * @returns { widgetId: { widgetData, widgetIndex, parentId, parentContent, isFreeWidget, hierarchy, parentBindForm }
         */
        widgetListFlat() {
            const widgetsFlat = getWidgetListFlat(this.widgetList)
            const widgetsHierarchy = getWidgetHierarchys(widgetsFlat)
            const pageData = this.pageData
            Object.keys(widgetsFlat).forEach(widgetId => {
                const hierarchy = widgetsHierarchy[widgetId]
                widgetsFlat[widgetId].hierarchy = hierarchy
                widgetsFlat[widgetId].parentBindForm = getWidgetParentBindForm({ widgetsFlat, widgetHierarchy: hierarchy })
            })
            return widgetsFlat
        },

        // 当前选中控件(返回 [{ widgetData, widgetIndex, parentId, parentContent }])
        selectWidget(state) {
            return state.selectWidgetIds.map(id => this.widgetListFlat[id])
        }
    },
    actions: {
        setAppData(data) {
            // 给每个页面添加顶部导航栏控件.
            Object.values(data.appData).forEach(item => {
                if (!!item?.hasOwnProperty('eles')) {
                    if (item?.eles?.[0]?.eles?.type !== 'custom-top-nav') {
                        const customTopNav = deepClone(customTopNavData)
                        createComponentAttr(customTopNav)
                        Object.assign(customTopNav.eles.customFeature, {
                            'title': item.customFeature.name,
                            'color': item.customFeature.titleColor,
                            'background-color': item.customFeature.titleBackgroundColor
                        })
                        item.eles.unshift(customTopNav)
                    }
                }
            })
            data.appData.version = appVersion
            this.appData = data.appData
            this.cataData = data.cataData
            this.pageId = data.cataData?.data?.find(item => item.pages.length > 0)?.pages?.[0]?.router || ''
            this.phoneZoom = data.phoneZoom || 1.15
            Object.assign(this.style, data.style || data.toolsObj.styleColor || {})
        },
        setWidgetList(list) {
            this.appData[this.pageId].eles = list
        },
        setPageId(id) {
            if (this.pageId !== id) this.selectWidgetIds = []
            this.pageId = id
        },

        // 获取app数据
        getAppData() {
            return new Promise(async (resolve, reject) => {
                const resApp = await getApp()
                if (resApp.Status === 1) {
                    const { OssGetUrl, HistoryId, Name, Description, AvaterUrl, IsDynamicData, DataJSON } = resApp.Data
                    const dataJson = JSON.parse(DataJSON || '{}')
                    this.historyId = HistoryId
                    this.appName = Name
                    this.appDescription = Description
                    this.appAvaterUrl = AvaterUrl
                    this.isDynamicData = IsDynamicData
                    this.modulePageConfigs = dataJson?.modulePageConfigs || {}

                    if (!!OssGetUrl) {
                        const resAppData = await getAppAliyun(OssGetUrl)
                        if (resAppData.data) {
                            const dataJson = resAppData?.data?.DataJson || {}
                            await this.setAppData(dataJson)
                        } else {
                            ElMessage.error('app数据不存在')
                        }
                    }
                    resolve(resApp)
                } else {
                    ElMessage.error(resApp.Message || '网络错误')
                    reject()
                }
            })
        },
        // 保存app数据
        saveAppData() {
            return new Promise(async (resolve, reject) => {
                const tabbarList = this.tabbarData?.list || []
                if (tabbarList.some(item => !item.router)) {
                    ElMessage({
                        message: '保存失败，底部导航项必须连接一个页面',
                        grouping: true,
                        type: 'error'
                    })
                    reject()
                    return
                }
                if ((tabbarList.length > 0) && (tabbarList.length < 2)) {
                    ElMessage({
                        message: '保存失败，底部导航关联页面必须为2-5个',
                        grouping: true,
                        type: 'error'
                    })
                    reject()
                    return
                }

                const saveData = {
                    DataJson: {
                        historyId: this.historyId,
                        appData: this.appData,
                        cataData: this.cataData,
                        appName: this.appName,
                        pageId: this.pageId,
                        phoneZoom: this.phoneZoom,
                        style: this.style,
                        // todo 待废弃属性
                        toolsObj: {
                            phoneZoom: this.phoneZoom
                        }
                    },
                    CataJson: this.cataData
                }

                const resSaveApp = await saveApp({
                    params: {
                        NeedNewVersion: 1,
                        DataJSON: JSON.stringify({
                            modulePageConfigs: this.modulePageConfigs
                        })
                    }
                })
                if (resSaveApp.Status === 1) {
                    this.historyId = resSaveApp.Data.HistoryId
                    saveAppAliyun({
                        url: resSaveApp.Data.OssPutUrl,
                        data: saveData
                    }).then(res => {
                        ElMessage({
                            message: '保存成功',
                            grouping: true,
                            type: 'success'
                        })
                        resolve()
                    }).catch(() => {
                        ElMessage({
                            message: '保存失败',
                            grouping: true,
                            type: 'error'
                        })
                        reject()
                    })
                } else {
                    ElMessage({
                        message: `保存失败，${resSaveApp.Message || '网络错误'}`,
                        grouping: true,
                        type: 'error'
                    })
                    reject()
                }
            })
        },
        // 获取模型变量方法集
        getFxMethods(ids = []) {
            return new Promise(async (resolve, reject) => {
                getModuleMethod(ids.join(',')).then(res => {
                    if (res.Status === 1) {
                        const methods = {}
                        res?.Data?.forEach(item => methods[item.id] = item)
                        this.fxMethods = methods
                        resolve(res)
                    } else {
                        reject(res)
                    }
                }).catch(() => {
                    reject()
                })
            })
        }
    }
})

export default useEditStore